package com.ittsang.utils;

import cn.hutool.core.bean.BeanUtil;
import com.ittsang.dto.UserDTO;
import jodd.net.HttpMethod;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);
            // 拦截
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("用户未登录");
            return false;
        }
        // 有用户，则放行
        // 2.基于TOKEN获取redis中的用户
        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash()
                .entries(key);

        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("用户未登录或者用户信息已过期，请登录。");
            response.setStatus(401);
            return false;
        }

        // 5.将查询到的Hash数据转为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        // 6.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        // 7.刷新token有效期
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return true;
    }
}
